package cn.bitkit.component.common;

import cn.bitkit.base.annotation.Dictionary;
import cn.bitkit.base.dictionary.BaseDictionary;
import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.base.util.ReflectUtil;
import cn.bitkit.base.util.StringUtil;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author changbo
 */
public class DictionaryHandler {


    public static void setAllDesc(Collection<?> beans){
        if(beans == null || beans.isEmpty()){
            return;
        }
        beans.forEach(DictionaryHandler::setAllDesc);
    }

    public static void setAllDesc(Object bean){
        List<Field> list = ReflectUtil.getAllFields(bean.getClass());
        list.forEach(field -> {
            String val = ReflectUtil.getValue(bean, field);
            if(StringUtil.isEmpty(val)){
                return;
            }
            Dictionary mark = field.getAnnotation(Dictionary.class);
            if(mark == null || !mark.value().isEnum()){
                return;
            }
            String descField = StringUtil.hasValue(mark.nameField()) ? mark.nameField() : field.getName()+mark.nameFieldAuto();
            Arrays.stream(mark.value().getEnumConstants()).filter(e -> e.getCode().equals(val)).findFirst().ifPresent(e -> {
                ReflectUtil.setValue(bean, descField, e.getDesc());
            });
        });
    }

    public static <T extends BaseDictionary> T getByCodeAndAssert(Class<T> enumClass, String key){
        T e = getByCode(enumClass, key);
        BusinessAssert.isNotNull(e, "字典不存在:"+key);
        return e;
    }

    public static <T extends BaseDictionary> T getByCode(Class<T> enumClass, String key){
        return Arrays.stream(enumClass.getEnumConstants())
                .filter(e -> e.getCode().equals(key))
                .findFirst().orElse(null);
    }

}
